package com.example.mybaitsplusdemo.controller;

import com.example.mybaitsplusdemo.entity.Users;
import com.example.mybaitsplusdemo.entity.authorities;
import com.example.mybaitsplusdemo.mapper.AuthoritiesMapper;
import com.example.mybaitsplusdemo.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class indexController {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private AuthoritiesMapper authoritiesMapper;
    @RequestMapping({"/index","/"})
    public String index(Authentication auth, Model model){
        model.addAttribute("username",auth.getName());
        model.addAttribute("password",auth.getPrincipal().toString());
        model.addAttribute("authorities",auth.getAuthorities());
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/sign-in")
    public String sign_in(){
        return "signin";
    }

    @PostMapping("/sign-in")
    public String sign_in(String username,String password,Model model){
        Users user=usersMapper.selectById(username);
        if(user!=null){
            model.addAttribute("message","用户名已存在");
            return "signin";
        }
        else {
            BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
            String encode= BCrypt.hashpw(password,BCrypt.gensalt());
            user=new Users(username,encode,true);
            authorities authorities=new authorities(username,"ROLE_ADMIN");

            usersMapper.insert(user);
            authoritiesMapper.insert(authorities);
            return "login";
        }

    }
}

